package com.tangkun.environment.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.tangkun.environment.R;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.CustomViewPager;
import com.tangkun.environment.view.OnImageTouchedListener;
import com.tangkun.environment.view.ZoomableImageView;

/**
 * @author tangkun
 * @ClassName: ImageActivity
 * @Description: TODO(大图页面)
 * @date 2016年5月5日 上午10:28:39
 */
public class ImageActivity extends BaseActivity {

    private TextView title;

    private ImageAdapter adapter;
    private CustomViewPager pager;

    private List<String> urlList = new ArrayList<>();
    /**
     * 有这个图片名称集合的时候顶部显示图片名称+张数，否则显示图片浏览+张数
     */
    private List<String> nameList = new ArrayList<>();

    private Context context;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);
        context = this;

        urlList = (List<String>) getIntent().getSerializableExtra("urlList");
        nameList = (List<String>) getIntent().getSerializableExtra("nameList");
        int index = (Integer) getIntent().getIntExtra("index", 0);

        adapter = new ImageAdapter(urlList);
        pager = (CustomViewPager) findViewById(R.id.image);
        pager.setAdapter(adapter);
        pager.setCurrentItem(index);

//        title = (TextView) findViewById(R.id.head_title);
//        if (nameList != null && nameList.size() > 0) {
//            title.setText(nameList.get(index) + "(" + (index + 1) + "/" + urlList.size() + ")");
//        } else {
//            title.setText("图片浏览(" + (index + 1) + "/" + urlList.size() + ")");
//        }
//        final TextView button = (TextView) findViewById(R.id.button);
//        button.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View arg0) {
//                try {
//                    DownloadAsyncTask task = new DownloadAsyncTask(button, new File(Helper.getRootPath(), "/download/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg"));
//                    task.execute(new URL(urlList.get(pager.getCurrentItem())));
//                } catch (Exception e) {
//
//                }
//            }
//        });

        pager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int index) {
//                if (nameList != null && nameList.size() > 0) {
//                    title.setText(nameList.get(index) + "(" + (index + 1) + "/" + urlList.size() + ")");
//                } else {
//                    title.setText("图片浏览(" + (index + 1) + "/" + urlList.size() + ")");
//                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });

    }

    private class DownloadAsyncTask extends AsyncTask<URL, Integer, Void> {

        private TextView button;
        private Context context;
        private File file;

        public DownloadAsyncTask(TextView button, File file) {
            this.button = button;
            this.context = button.getContext();
            this.file = file;
        }

        @Override
        protected void onPreExecute() {
            button.setEnabled(false);
        }

        @Override
        protected Void doInBackground(URL... params) {
            URL url = params[0];

            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);

                if (conn.getResponseCode() == 200) {

                    InputStream is = conn.getInputStream();

                    if (is == null) {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                Toast.makeText(context, "图片下载失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                        cancel(true);
                        return null;
                    }

                    if (file.getParentFile().exists() == false) {
                        file.getParentFile().mkdirs();
                    }

                    FileOutputStream fos = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }
                    is.close();
                    fos.close();
                }

            } catch (Exception e) {
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(context, "图片下载失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            return null;

        }

        @Override
        protected void onCancelled(Void v) {
            button.setEnabled(true);
        }

        @Override
        protected void onPostExecute(Void v) {
            button.setEnabled(true);
            try {

                MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getPath(), file.getName(), "");

                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
            } catch (Exception e) {

            }
            Toast.makeText(context, "图片已下载", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
        }
    }

    public void setUrlList(List<String> urlList) {
        adapter.setUrlList(urlList);
        adapter.notifyDataSetChanged();
    }

    private class ImageAdapter extends PagerAdapter {

        public ImageAdapter(List<String> urlList) {
            this.urlList = urlList;
        }

        private List<String> urlList;

        public List<String> getUrlList() {
            return urlList;
        }

        public void setUrlList(List<String> urlList) {
            this.urlList = urlList;
        }

        @Override
        public int getCount() {
            return urlList == null ? 0 : urlList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == (View) obj;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View v = getLayoutInflater().inflate(R.layout.item_pic_list, null);
            final ZoomableImageView imageView = (ZoomableImageView) v.findViewById(R.id.imageView);
            //单击关闭页面
            imageView.setOnImageTouchedListener(new OnImageTouchedListener() {
                @Override
                public void onImageTouched() {
                    finish();
                }
            });
            if (!urlList.get(position).toString().contains("/storage/emulated") && (urlList.get(position).toString().endsWith(".png") || urlList.get(position).toString().endsWith(".jpg"))) {
                //表示网络半路径
                //refer to blog http://blog.csdn.net/qq_19711823/article/details/50856236
                LogUtils.e("ImageActivity 网络图片全路径:" + GlobalUrl.IMG_URL + urlList.get(position));
                Glide.with(ImageActivity.this).load(GlobalUrl.IMG_URL + urlList.get(position)).asBitmap().into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        imageView.setImageBitmap(resource);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_place_holder);
                        imageView.setImageBitmap(bitmap);
                    }
                });
            } else {
                //表示本地文件地址
                try {
                    Bitmap bitmap = Utils.getBitmapFromUrl(urlList.get(position).toString());
                    LogUtils.e("ImageActivity 本地图片全路径:" + GlobalUrl.IMG_URL + urlList.get(position) + "  to bitmap isNull:" + (bitmap == null));
                    imageView.setImageBitmap(bitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            ((ViewPager) container).addView(v, 0);
            return v;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pager.removeAllViews();
    }

}
